<template>
  <div class="search">
    <form action="/">
      <van-search
          v-model="searchText"
          show-action
          shape="round"
          background="#3a8ee6"
          placeholder="请输入搜索关键词"
          @search="onSearch(searchText)"
          @cancel="$router.back()"
          @focus="isResultShow=false"
      />
    </form>
<!--    搜索结果-->
    <search-result v-if="isResultShow" :search-text="searchText"/>
<!--    联想建议-->
    <search-suggestion v-else-if="searchText" :search-text="searchText" @search="onSearch"/>
<!--搜索历史-->
    <search-history :SearchHistories="SearchHistories" @search="onSearch" @update-histories="SearchHistories=$event" v-else/>


  </div>
</template>

<script>
import SearchSuggestion from "@/components/search/componets/SearchSuggestion";
import SearchHistory from "@/components/search/componets/SearchHistory";
import SearchResult from "@/components/search/componets/SearchResult";

import {setItem,getItem} from "@/utils/storage";
import {getSearchHistories} from '@/api/search'
import {mapState} from 'vuex'
export default {
  name: "Searchindex",
  components:{
    SearchSuggestion,
    SearchHistory,
    SearchResult,
  },
  data() {
    return {
      searchText: '',
      isResultShow:false,
      SearchHistories:[]
    };
  },
  created() {
    this.loadSearchHistories()
  },
  watch:{
    SearchHistories(){
      setItem('search-histroy',this.SearchHistories)
    }
  },
  methods: {
    onSearch(searchText) {
      this.searchText=searchText
      const index=this.SearchHistories.indexOf(searchText)
      if (index!==-1){
        this.SearchHistories.splice(index,1)
      }
      this.SearchHistories.unshift(searchText)
      setItem('search-histroy',this.SearchHistories)
      this.isResultShow=true
    },
    async loadSearchHistories(){
      let searchHistories=getItem('search-histroy')||[]
      if (this.user){
        const {data}=await getSearchHistories()
        searchHistories=[...new Set([...searchHistories,...data.data.keywords])]
      }

      this.SearchHistories=searchHistories
    }
  },
  computed:{
    ...mapState
  }
}
</script>

<style scoped lang="less">
</style>